<template>
  <div :style="getSwipeSize"
       :class="styles.warp"
       @mouseenter="swipeMouseover"
       @mouseleave="swipeMouseleave"
  >
    <div :class="styles['control-bar']" v-show="showControlBar">
      <img src="../../../../assets/left.svg" @click="index--">
      <img src="../../../../assets/right.svg" @click="index++">
    </div>
    <div :class="styles['slider-list']" :style="{...getSliderListWidth,...getSliderOffset}" ref="slider">
      <slot></slot>
    </div>
  </div>
</template>

<script>
  import {SWIPE_DATA} from '@util/constant'
  import styles from './swipe.scss'

  export default {
    name: "swipe",
    model: {},
    props: {
      height: {
        type: Number,
        default: 470
      },
      width: {
        type: Number,
        default: 600
      },
      swipeData: {
        type: Array,
        default: function () {
          return SWIPE_DATA
        }
      },
      auto: {
        type: Boolean,
        default: true
      },
      time: {
        type: Number,
        default: 3000
      },
      showControlBar: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        styles,
        index: 0,
        count: 0
      }
    },
    computed: {
      getSwipeSize: function () {
        return {height: this.height + 'px', width: this.width + 'px'}
      },
      getSliderListWidth: function () {
        return {width: this.width * this.count + 'px'}
      },
      getSliderOffset: function () {
        return {transform: `translateX(-${this.width * this.index}px)`}
      }
    },
    beforeCreate: function () {

    },
    created: function () {
    },
    beforeMount: function () {

    },
    mounted: function () {
      this.count = this.$refs.slider.children.length
      if (this.auto) {
        this.playSwipe()
      }
    },
    updated: function () {

    },
    activated: function () {

    },
    deactivated: function () {

    },
    beforeDestroy: function () {

    },
    destroyed: function () {

    },
    methods: {
      playSwipe() {
        setTimeout(() => {
          this.index++;
          this.playSwipe()
          // while自旋 判断是否暂停
        }, this.time)
      },
      swipeMouseover(){
        this.$emit('swipeMouseover')
      },
      swipeMouseleave(){
        this.$emit('swipeMouseleave')
      }
    },
    watch: {
      index: function () {
        if (this.index >= this.count) {
          this.index = 0
        } else if (this.index < 0) {
          this.index = this.count - 1
        }
      }
    }
  }
</script>

<style scoped>

</style>
